package com.wiscamp.ninechapters.problems.math;

import com.wiscamp.ninechapters.common.core.ParseHelper;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;
import java.math.BigDecimal;

/**
 * 等式方程的解
 */
@Data
public class LatexEquationSolution implements Serializable {
    private static Logger logger = LoggerFactory.getLogger(LatexEquationSolution.class);

    /**
     * 变量
     */
    private String variable;

    /**
     * 方程解的值
     */
    private BigDecimal value = new BigDecimal(0);

    /**
     * 方程解序号
     */
    private int index = 0;

    /**
     * 是否是方程解的值的近似数 （待定）
     */
    private boolean approximateNumber = false;

    public LatexEquationSolution(String variable, BigDecimal value, int index, boolean approximateNumber) {
        this.approximateNumber = approximateNumber;
        this.index = index;
        this.value = value;
        this.variable = variable;
    }


    public String getLatex() {
        if (this.index >= 1)
            return String.format("%s_%d=%s", variable, index, value.stripTrailingZeros());
        else
            return String.format("%s=%s", variable, value.stripTrailingZeros());
    }

    public static LatexEquationSolution parseEquationSolution(String latexText) {
        var tempStr = latexText.replace(" ", "").trim();
        var variableText = "";
        var indexText = "";
        var valueText = "";
        if (tempStr.contains("_")) {
            int leftIndex = tempStr.indexOf("_");
            int rightIndex = tempStr.indexOf("=");
            variableText = tempStr.substring(0, leftIndex);
            indexText = tempStr.substring(leftIndex + 1, rightIndex);
            valueText = tempStr.substring(rightIndex + 1);
            logger.debug("parsing equation solution. Variable: {} Index: {} Value: {}", variableText, indexText, valueText);
        } else {
            int leftIndex = tempStr.indexOf("=");
            variableText = tempStr.substring(0, leftIndex);
            indexText = "0";
            valueText = tempStr.substring(leftIndex);
            logger.debug("parsing equation solution. Variable: {} Index: {} Value: {}", variableText, indexText, valueText);
        }
        int index = ParseHelper.parseInteger(indexText);
        BigDecimal value = ParseHelper.parseBigDecimal(valueText);
        return new LatexEquationSolution(variableText, value, index, false);
    }

}
